package controllers;

import models.Game;
import models.Player;
import play.db.jpa.JPA;
import play.mvc.Controller;

import javax.persistence.EntityManager;

/**
 * @author Einar Tryggvi Leifsson <einarl10@ru.is>
 * @version 1.6
 * @since 22.11.2011
 */
public class TicTacToe extends Controller
{
	public static void index()
	{
		if (session.get("gameid") == null) {
			TicTacToe.newGame();
		}
		else {
			Game game = Game.findById(Long.valueOf(session.get("gameid")));
			game.lastplay = session.getId();
			game.save();
			render();
		}
	}

	public static void newGame()
	{
		if (session.get("gameid") == null) {
			Game game = new Game();
			game.lastplay = session.getId();
			game.status = "";
			game.save();
			long id = game.getId();
			session.put("gameid", id);
		}
		else {
			TicTacToe.index();
		}
	}

	public static void joinGame(long gameID)
	{
		if (gameID > 0) {
			session.put("gameid", gameID);
			TicTacToe.index();
		}
	}

	public static void getStatus()
	{
		if (session.get("gameid") != null) {
			Game game = Game.findById(Long.valueOf(session.get("gameid")));
			if (game != null) {
				while (session.getId().equals(game.lastplay)) {
					game = Game.findById(Long.valueOf(session.get("gameid")));
					await(1000);
				}
				renderJSON(game);
			}
		}
		renderJSON(false);
	}

	public static void doMove(String json)
	{
		if (session.get("gameid") != null && json != null) {
			Game game = Game.findById(Long.valueOf(session.get("gameid")));
			if (game.lastplay.equals(session.getId())) {
				game.lastplay = session.getId();
				game.status = json;
				game.save();
				renderJSON(true);
			}
		}
		renderJSON(false);
	}
}
